package com.llmcu.tuling.architect.concurrent.computer;

import java.util.Arrays;

/**
 * 测试cpu空间局部性
 * 二维数组求和，一种是按行取数据，一种是按列取数据
 * 按行取数据比按列取数据快，从而体现cpu存在空间局部性
 *
 * @author liuling
 * @date 2024/7/7 17:35
 */
public class TestSpatialLocality {
    public static void main(String[] args) {
        int size1 = 1024 * 1024;
        int size2 = 6;
        long[][] array = new long[size1][size2];
        initArray(array);

        int count = 20;
        boolean[] countArray = new boolean[count];
        for (int i = 0; i < count; i++) {
            long startTime = System.currentTimeMillis();
            long result = 0L;
            for (int i1 = 0; i1 < size1; i1++) {
                for (int j = 0; j < size2; j++) {
                    result += array[i1][j];
                }
            }
            long endTime = System.currentTimeMillis();

            long startTime2 = System.currentTimeMillis();
            long result2 = 0L;
            for (int j = 0; j < size2; j++) {
                for (int k = 0; k < size1; k++) {
                    result2 += array[k][j];
                }
            }
            long endTime2 = System.currentTimeMillis();

            if (result != result2) {
                throw new RuntimeException("not equals");
            }

            countArray[i] = (endTime - startTime) < (endTime2 - startTime2);
        }
        for (boolean b : countArray) {
            if (b) {
                System.out.print(b);
            } else {
                System.err.print(b);
            }
        }
    }

    private static void initArray(long[][] array) {
        for (long[] longs : array) {
            Arrays.fill(longs, 1L);
        }
    }
}
